package com.example.newinfinity.View.DrawShape

import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import com.example.newinfinity.IconModel.IconState
import com.example.newinfinity.MyViewModel.DrawViewModel

//橡皮擦 PorterDuffXForMode混合模式
class EraserShape() : Shape() {
    //橡皮擦矩形视图的位置是实时获取move的位置并上下左右扩大边框
    private var mLeft = 0f
    private var mTop = 0f
    private var mRight = 0f
    private var mBottom = 0f
    var mOpenSize = 0f //扩大的距离
    private var mRectanglePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        this.color = Color.parseColor("#FFE0FF")
    }


    //松手up时用于显示橡皮擦形状的矩形应该消失 记录其显示状态
    //IconState == IconState.NORMAL时则隐藏矩形
    private var eraserRectShowState = IconState.SELECTED  //可以显示
    override fun changeEraserRectShowState() {
        eraserRectShowState = IconState.NORMAL  //修改显示状态
    }

    override fun setStartPoint(x: Float, y: Float) {
        super.setStartPoint(x, y)
        mPath.reset()
        mPath.moveTo(startX, startY)
    }

    override fun setEndPoint(x: Float, y: Float) {
        super.setEndPoint(x, y)
        //更新橡皮擦矩形显示的位置
        mLeft = endX - mOpenSize
        mTop = endY - mOpenSize
        mRight = endX + mOpenSize
        mBottom = endY + mOpenSize
        mPath.lineTo(endX, endY)

        //用于混合消除实现橡皮擦功能的矩形
        mPaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
        mPaint.style = Paint.Style.STROKE
        mPaint.strokeWidth = DrawViewModel.getDrawViewModel().eraserStrokeWidth
    }

    override fun draw(canvas: Canvas) {
        canvas.drawPath(mPath, mPaint)
        //视图上显示的橡皮擦矩形
        mOpenSize = DrawViewModel.getDrawViewModel().eraserStrokeWidth / 2
        if (eraserRectShowState == IconState.SELECTED) {
            canvas.drawRect(mLeft, mTop, mRight, mBottom, mRectanglePaint)
        }
    }

    override fun containsPointInPath(x: Float, y: Float): Boolean {
        return super.containsPointInPath(x, y)
    }
}